//消息弹窗
function layer_msg(res) {
    parent.parent.layer.msg(res.msg);
    var jump = res.jump,jump_url = res.jump_url||false;
    if(jump=='#'){
        window.location.reload();
    }
    else if(jump!=undefined&&jump!=""&&jump!='#') {
        if(jump_url){
            window.location.href = jump;
        }
        else{
            window.location.href = window.public_url + jump;
        }
    }
    $("body").data("shadow-flg",0);
}
//弹窗函数
function layer_open(res){
    var jump = res.jump,jump_url = res.jump_url||false,iframe_index=res.index||0;
    if(iframe_index==1){
        parent.layer.open({
            content:res.msg,
            yes:function (index) {
                if(jump=='#'){
                    window.location.reload();
                }
                else if(jump!=undefined&&jump!=""&&jump!='#'){
                    if(jump_url){
                        window.location.href = jump;
                    }
                    else{
                        window.location.href = window.public_url + jump;
                    }
                }
                $("body").data("shadow-flg",0);
                parent.layer.close(index);
            },
            cancel:function (index) {
                if(jump=='#'){
                    window.location.reload();
                }
                else if(jump!=undefined&&jump!=""&&jump!='#'){
                    if(jump_url){
                        window.location.href = jump;
                    }
                    else{
                        window.location.href = window.public_url + jump;
                    }
                }
                $("body").data("shadow-flg",0);
                parent.layer.close(index);
            }
        });
    }
    else if (iframe_index==2){
        parent.parent.layer.open({
            content:res.msg,
            yes:function (index) {
                if(jump=='#'){
                    window.location.reload();
                }
                else if(jump!=undefined&&jump!=""&&jump!='#'){
                    if(jump_url){
                        window.location.href = jump;
                    }
                    else{
                        window.location.href = window.public_url + jump;
                    }
                }
                $("body").data("shadow-flg",0);
                parent.parent.layer.close(index);
            },
            cancel:function (index) {
                if(jump=='#'){
                    window.location.reload();
                }
                else if(jump!=undefined&&jump!=""&&jump!='#'){
                    if(jump_url){
                        window.location.href = jump;
                    }
                    else{
                        window.location.href = window.public_url + jump;
                    }
                }
                $("body").data("shadow-flg",0);
                parent.parent.layer.close(index);
            }
        });
    }
    else {
        layer.open({
            content:res.msg,
            yes:function (index) {
                if(jump=='#'){
                    window.location.reload();
                }
                else if(jump!=undefined&&jump!=""&&jump!='#'){
                    if(jump_url){
                        window.location.href = jump;
                    }
                    else{
                        window.location.href = window.public_url + jump;
                    }
                }
                $("body").data("shadow-flg",0);
                layer.close(index);
            },
            cancel:function (index) {
                if(jump=='#'){
                    window.location.reload();
                }
                else if(jump!=undefined&&jump!=""&&jump!='#'){
                    if(jump_url){
                        window.location.href = jump;
                    }
                    else{
                        window.location.href = window.public_url + jump;
                    }
                }
                $("body").data("shadow-flg",0);
                layer.close(index);
            }
        });
    }
}
// 表格参数回调产生的值
function auto_iframe(id,res) {
    var height = $("body").height();
    var iframe = $("#"+id ,parent.document);
    if(iframe.hasClass('auto-iframe')){
        $("#"+id ,parent.document).height(height+50);
    }
    var excelDom = $("#"+id).find('.import-excel .card ul');
    var excel = res.excel||[];
    for(var i=0;i<excel.length;i++){
        var li = "<li><a href='"+excel[i].url+"'>"+excel[i].filename+"</a></li>";
        $(li).appendTo(excelDom);
    }

    var style = $('.table-iframe-dom style');
    style.html(style.html());

    //复制按钮
    if($(".copy-btn").length>0){
        var btns = document.querySelectorAll('.copy-btn');
        var clipboard = new ClipboardJS(btns);
        clipboard.on('success', function(e) {
            parent.parent.layer.msg('复制成功！');
        });
        clipboard.on('error', function(e) {
            parent.parent.layer.msg('复制失败！');
        });
    }
}
//开关模板
function switchTpl(d,main,text) {
    var text = text||'是|否';
    if(d[main]==0){
        var doc = ' <input type="checkbox" class="switch'+d.id+'" lay-skin="switch" lay-text=' +text +'>';
    }
    else {
        var doc = ' <input type="checkbox" class="switch'+d.id+'" checked  lay-skin="switch" lay-text=' +text +'>';
    }
    form.on('switch',function (res) {
        console.log(res.elem.className);
        var className = res.elem.className;
        var id = className.split('switch')[1];
        var is_checked = res.elem.checked,main_val=null;
        if(is_checked){main_val = 1;} else {main_val =0;}
        var data = {};
        data[main] = main_val;
        data.id = id;
        $.ajax({
            url:'switchBtn',
            dataType:'json',
            data:data,
            success:function (res) {
                if(res.code==0){
                    layer.msg(res.msg);
                    if(is_checked){
                        $(".switch"+id).prop('checked','');
                        form.render();
                    }
                    else {
                        $(".switch"+id).prop('checked','checked');
                        form.render();
                    }
                }
            }
        });
    });
    return doc;
}
// 判断是否是IE浏览器
function browserIsIe() {
    if (!!window.ActiveXObject || "ActiveXObject" in window)
        return true;
    else
        return false;
}
//设置cookie
function setCookie(name,value,Hours){
    var Hours=Hours||6;
    var exp = new Date();
    exp.setTime(exp.getTime() + Hours*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
//获取cookie
function getCookie(name){
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}
//删除cookie
function delCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if(cval!=null)
        document.cookie = name + "="+cval+";expires="+exp.toGMTString();
}
//打印数据
function al(str){
    alert(str)
}
//简化调试
function log(str) {
    console.log(str);
}
//加载页面load
function loadFile(idKey,file){
    $(idKey).load(file);
}
//获取URL参数
function getUrlPath(){
    var url = window.location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            //就是这句的问题
            theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
            //之前用了unescape()
            //才会出现乱码
        }
    }
    return theRequest;
}

//去除数组空值
function clearArrayEmpty(array){
    for(var i = 0 ;i<array.length;i++){
        if(array[i] == "" || typeof(array[i]) == "undefined"){
            array.splice(i,1);
            i = i-1;
        }
    }
    return array;
}
//去除数组重复的值
function uniqueArray(arr){
    var tmp = new Array();
    for(var m in arr){
        tmp[arr[m]]=1;
    }
    //再把键和值的位置再次调换
    var tmparr = new Array();
    for(var n in tmp){
        tmparr.push(n);
    }
    return tmparr;
}
function isMobile() {
    if( navigator.userAgent.match(/Android/i)
        || navigator.userAgent.match(/webOS/i)
        || navigator.userAgent.match(/iPhone/i)
        || navigator.userAgent.match(/iPad/i)
        || navigator.userAgent.match(/iPod/i)
        || navigator.userAgent.match(/BlackBerry/i)
        || navigator.userAgent.match(/Windows Phone/i)
    ){
        return true;
    }
    else {
        return false;
    }
}
//手机验证码
function checkMobile(sMobile){
    if(!(/^1[3|4|5|8][0-9]\d{4,8}$/.test(sMobile))){
        return false;
    }else{
        return true;
    }
}

//页面刷新；

function  reload() {
    location.reload();
}
function href(a) {
    window.location.href=a
}


//随机数区间min ≤ r ≤ max
function RandomNumBoth(Min,Max){
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}

//随机数区间min ≤ r < max
function RandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.floor(Rand * Range); //舍去
    return num;
}
//随机数区间min < r ≤ max
function RandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    if(Math.round(Rand * Range)==0){
        return Min + 1;
    }
    var num = Min + Math.round(Rand * Range);
    return num;
}
//随机数区间min < r < max
function RandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    if(Math.round(Rand * Range)==0){
        return Min + 1;
    }else if(Math.round(Rand * Max)==Max)
    {
        index++;
        return Max - 1;
    }else{
        var num = Min + Math.round(Rand * Range) - 1;
        return num;
    }
}

//html转码
function html_encode(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&gt;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    s = s.replace(/\n/g, "<br>");
    return s;
}


//浮点保留小数。
// src=参数，pos：保留位数
function fomatFloat(src,pos){
    return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);
}

function array_remove_repeat(a) { // 去重
    var r = [];
    for(var i = 0; i < a.length; i ++) {
        var flag = true;
        var temp = a[i];
        for(var j = 0; j < r.length; j ++) {
            if(temp === r[j]) {
                flag = false;
                break;
            }
        }
        if(flag) {
            r.push(temp);
        }
    }
    return r;
}

function array_intersection(a, b) { // 交集
    var result = [];
    for(var i = 0; i < b.length; i ++) {
        var temp = b[i];
        for(var j = 0; j < a.length; j ++) {
            if(temp === a[j]) {
                result.push(temp);
                break;
            }
        }
    }
    return array_remove_repeat(result);
}

function array_union(a, b) { // 并集
    return array_remove_repeat(a.concat(b));
}

function array_difference(a, b) { // 差集 a - b
    //clone = a
    var clone = a.slice(0);
    for(var i = 0; i < b.length; i ++) {
        var temp = b[i];
        for(var j = 0; j < clone.length; j ++) {
            if(temp === clone[j]) {
                //remove clone[j]
                clone.splice(j,1);
            }
        }
    }
    return array_remove_repeat(clone);
}
//创建script
function create_script(url) {
    var scriptFile = document.createElement('script');
    scriptFile.setAttribute("type","text/javascript");
    scriptFile.setAttribute("src",url);
    document.getElementsByTagName("head")[0].appendChild(scriptFile);
}
//创建css
function loadCss(file){
    var cssTag = document.getElementById('loadCss');
    var head = document.getElementsByTagName('head').item(0);
    if(cssTag) head.removeChild(cssTag);
    var css = document.createElement('link');
    css.href = file;
    css.rel = 'stylesheet';
    css.type = 'text/css';
    head.appendChild(css);
}
//是否是移动端
function goPAGE() {
    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)))
    {
        /*window.location.href="你的手机版地址";*/
        return 'mobile';
    }
    else {
        /*window.location.href="你的电脑版地址";    */
        return 'pc';
    }
}

//数组分类
function arrcount(_arr) {
    var _res = []; //
    _arr.sort();
    for (var i = 0; i < _arr.length;) {
        var count = 0;
        for (var j = i; j < _arr.length; j++) {
            if (_arr[i] == _arr[j]) {
                count++;
            }
        }
        _res.push([_arr[i], count]);
        i += count;
    }
    var _newArr = [];
    for (var i = 0; i < _res.length; i++) {
        // console.log(_res[i][0] + "重复次数:" + _res[i][1]);
        _newArr.push({
            val:_res[i][0],
            count: _res[i][1]
        });
    }
    return _newArr;
}
/**
 * 异步加载
 */
function parallelLoadScripts(scripts,callback) {
    var self = this;
    if ("object" != typeof scripts) {
        scripts = [scripts];
    }
    var value = doc.getElementsByTagName("head").item(0) || doc.documentElement;
    var scptElt = [];
    var counter = 0;
    var i = 0;
    for (;i < scripts.length;i++) {
        scptElt[i] = doc.createElement("script");
        scptElt[i].setAttribute("type", "text/javascript");
        scptElt[i].onload = scptElt[i].onreadystatechange = function() {
            if (!(self.browser().isIEBelow10() && ("loaded" !== this.readyState && "complete" !== this.readyState))) {
                counter++;
                this.onload = this.onreadystatechange = null;
                if (counter === scripts.length) {
                    if ("function" == typeof callback) {
                        callback();
                    }
                }
            }
        };
        scptElt[i].setAttribute("src", scripts[i]);
        value.appendChild(scptElt[i]);
    }
}
//同步加载
function seriesLoadScripts() {
    if ("object" != typeof scripts) {
        scripts = [scripts];
    }
    var value = doc.getElementsByTagName("head").item(0) || doc.documentElement;
    var elems = new Array;
    var e = scripts.length - 1;
    var load = function(i) {
        elems[i] = doc.createElement("script");
        elems[i].setAttribute("type", "text/javascript");
        elems[i].onload = elems[i].onreadystatechange = function() {
            this.onload = this.onreadystatechange = null;
            if (i != e) {
                load(i + 1);
            } else {
                if ("function" == typeof callback) {
                    callback();
                }
            }
        };
        elems[i].setAttribute("src", scripts[i]);
        value.appendChild(elems[i]);
    };
    load(0);
}
// 原生ajax
function ajax(opts) {
    // 创建ajax对象
    var xhr = null,
        abortTimeout = null,
        empty =function(){},
        ajax_url = "",
        opts = {
            type : ( opts.type && opts.type.toUpperCase() ) || 'GET',
            url : opts.url || "",
            data : opts.data || "", //query
            dataType : opts.dataType || 'json',
            success : opts.success || empty,
            error : opts.error || empty,
            timeout : opts.timeout || 10000 //默认超时时间：30S ，与产品交互保持一致
        };
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    opts.data = formatParams( opts.data );
    if (opts.type == 'GET') {
        if(opts.url.indexOf("?")>-1){
            if( opts.data =="" ){
                ajax_url = opts.url;
            } else {
                ajax_url = opts.url + '&' + opts.data;
            }
        } else {
            ajax_url = opts.url + '?' + opts.data;
        }
        xhr.open('GET', ajax_url , true);
        xhr.send();

    } else if (opts.type == 'POST') {
        xhr.open('POST', opts.url, true);
        // 如果需要像 html 表单那样 POST 数据，请使用 setRequestHeader() 来添加 http 头。
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send( opts.data );
    }

    // 处理返回数据
    xhr.onreadystatechange = function () {
        /*
         ** 每当readyState改变时，就会触发onreadystatechange事件
         ** readyState属性存储有XMLHttpRequest的状态信息
         ** 0 ：请求未初始化
         ** 1 ：服务器连接已建立
         ** 2 ：请求已接受
         ** 3 : 请求处理中
         ** 4 ：请求已完成，且相应就绪
         */
        if (xhr.readyState == 4) {
            var res,error;
            xhr.onreadystatechange = empty;
            clearTimeout( abortTimeout );
            // console.log( "xhr.status: " , xhr.status );
            /*
             ** Http状态码
             ** 1xx ：信息展示
             ** 2xx ：成功
             ** 3xx ：重定向
             ** 4xx : 客户端错误
             ** 5xx ：服务器端错误
             */
            // var protocol = /^([\w-]+:)\/\//.test(opts.url) ? RegExp.$1 : window.location.protocol;
            // if ( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:') ) {
            if ( (xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 ) {
                res = xhr.responseText; // xhr.responseText 和 xhr.response 结果相同
                try {
                    // console.info( "snsnav request success" );
                    if( opts.type == 'GET' ){
                        if( opts.dataType == "json" ){
                            res = JSON.parse( xhr.responseText );
                        } else if ( opts.dataType == 'script' ) {
                            // http://perfectionkills.com/global-eval-what-are-the-options/
                            (1,eval)(res);
                        } else if ( opts.dataType == 'xml' ) {
                            res = xhr.responseXML;
                        }
                    }
                    else if( opts.type == 'POST' ){
                        if( opts.dataType == "json" ){
                            res = JSON.parse( xhr.responseText );
                        } else if ( opts.dataType == 'script' ) {
                            (1,eval)(res);
                        } else if ( opts.dataType == 'xml' ) {
                            res = xhr.responseXML;
                        }
                    }
                } catch (e) {
                    error = e;
                }
                if( error ){
                    opts.error( error, '参数错误！' , xhr );
                } else {
                    opts.success( res );
                }
            } else {
                // opts.error( xhr.statusText || 'unknown' , xhr.status ? 'error' : 'abort' , xhr );
                // xhr.status=0时，相关介绍：http://www.w3.org/TR/XMLHttpRequest/
                // The status attribute must return the result of running these steps:
                // 1、If the state is UNSENT or OPENED, return 0.
                // 2、If the error flag is set, return 0.
                // 3、Return the HTTP status code.
                // var xhr_status = xhr.status || 'unknown';

                switch (xhr.status){
                    case 301:
                        alert('(code:301)永久重定向。');
                        break;
                    case 302:
                        alert('(code:302)临时重定向。');
                        break;
                    case 303:
                        alert('(code:303)请求资源存在另一个URI。');
                        break;
                    case 307:
                        alert('(code:307)临时重定向。');
                        break;
                    case 400:
                        alert('(code:400)报文存在语法错误或参数错误。');
                        break;
                    case 401:
                        alert('(code:401)发送的请求需要有HTTP认证信息或者是认证失败。');
                        break;
                    case 403:
                        alert('(code:403)禁止访问。');
                        break;
                    case 404:
                        alert('(code:404)数据获取/输入失败，没有此服务。');
                        break;
                    case 500:
                        alert('(code:500)服务器故障或Web应用故障。');
                        break;
                    case 503:
                        alert('(code:503)服务器超负载或停机维护。');
                        break;
                    case 504:
                        alert('(code:504)数据获取/输入失败，服务器没有响应。');
                        break;
                    default:
                        opts.error(opts.error('服务器错误状态:'+xhr.status));
                        break;
                }
            }
        }
    };
    // function ajaxError( error, type, xhr ){ }
    // opts.error( error, 'parsererror',xhr );
    // type: "timeout", "error", "abort", "parsererror"
    if (opts.timeout > 0){ //设置超时时间
        abortTimeout = setTimeout(function(){
            xhr.onreadystatechange = empty;
            //取消当前响应，关闭连接并且结束任何未决的网络活动
            xhr.abort();
            //请求时间 超过前端设置的超时时间
            opts.error('请求超时！','timeout',xhr);
        }, opts.timeout);
    }
    return xhr;
    //参数格式化
    function formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
        }
        arr.push(("v=" + Math.random()).replace(".",""));
        return arr.join("&");
    }
}
//参数格式化
function formatParams(data) {
    var arr = [];
    for (var name in data) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    arr.push(("v=" + Math.random()).replace(".",""));
    return arr.join("&");
}
//判断是iOS 还是安卓
function phoneType() {
    var u = navigator.userAgent,res='';
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    (!isiOS) ?  res = 'android' : res = 'ios';
    return res;
}
//时间戳转时间
function getLocalTime(nS) {
    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
//当前时间戳和时间
function nowTimeFun(sort) {
    var sort = sort||1;
    var timestamp = Date.parse(new Date());
    //类型1:前端时间戳
    if(sort==1){
        return timestamp;
    }
    //类型2:后端时间戳
    if(sort==2){
        timestamp = String(timestamp);
        timestamp=timestamp.slice(0,10);
        timestamp = parseInt(timestamp);
        return timestamp;
    }
    //类型3：当前时间
    if(sort==3){
        timestamp = String(timestamp);
        timestamp=timestamp.slice(0,10);
        return getLocalTime(timestamp);
    }
}
//浏览器内核
function browser() {
    var broName = '',strStart = 0,strStop = 0,temp = '',userAgent = window.navigator.userAgent,system='other';
    // Firefox
    if (userAgent.indexOf('Firefox') > -1) {
        strStart = userAgent.indexOf('Firefox');
        system='Firefox';
        temp = userAgent.substring(strStart);
        broName = temp.replace('Firefox/', '');
    }
    //Chrome浏览器
    if (userAgent.indexOf('WOW') < 0 && userAgent.indexOf("Edge") < 0) {
        isChrome = true;
        /*broName = 'Chrome浏览器';*/
        strStart = userAgent.indexOf('Chrome');
        strStop = userAgent.indexOf(' Safari');
        system = 'Chrome'
        temp = userAgent.substring(strStart, strStop);
        broName = temp.replace('Chrome/', '');
    }
    //Edge
    if (userAgent.indexOf('Edge') > -1) {
        strStart = userAgent.indexOf('Edge');
        system='Edge';
        temp = userAgent.substring(strStart);
        broName = temp.replace('Edge/', '');
    }
    //360极速模式可以区分360安全浏览器和360极速浏览器
    if (userAgent.indexOf('WOW') > -1 && userAgent.indexOf("NET") < 0 && userAgent.indexOf("Firefox") < 0) {
        if(navigator.javaEnabled()){
            system = '360安全浏览器-极速模式';
        }else{
            system = '360极速浏览器-极速模式';
        }
    }
    //360兼容
    if (userAgent.indexOf('WOW') > -1 && userAgent.indexOf("NET") >-1 && userAgent.indexOf("MSIE") > -1 && userAgent.indexOf("rv") < 0) {
        system = '360兼容模式';
    }
    //IE浏览器
    if (userAgent.indexOf('NET') > -1 && userAgent.indexOf("rv") > -1) {
        /*broName = 'IE浏览器'; */
        strStart = userAgent.indexOf('rv');
        strStop = userAgent.indexOf(')');
        system='Edge';
        temp = userAgent.substring(strStart, strStop);
        broName = temp.replace('rv:', '版本号');
    }
    //UC浏览器
    if(userAgent.indexOf("UCBrowser")> -1){
        system='UCBrowser';
    }
    //QQ浏览器
    if(userAgent.indexOf("MQQBrowser")> -1){
        system='MQQBrowser';
    }
    //Sogou浏览器
    if(userAgent.indexOf("SogouBrowser")> -1){
        system='SogouBrowser';
    }
    //SogouBrowser
    if(userAgent.indexOf("SogouMobileBrowser") > -1){
        system='SogouMobileBrowser';
    }
    //WeixinX5浏览器
    var excludes = userAgent.toLowerCase();
    if(excludes.indexOf("micromessenger")> -1){
        system='WeixinX5Browser';
    }
    //QQZone
    if(userAgent.indexOf("QZONEJSSDK") > -1){
        system='QQZone';
    }
    //Safari
    if(userAgent.match(/^Mozilla\/5.0 \(.*?\) AppleWebKit\/.*? \(.*?\) Version\/.*? Mobile\/.*? Safari\/\d+\.\d+\.\d+?$/)!=null){
        system='Safari';
    }
    //OperaIOS
    if(userAgent.indexOf("OPiOS") > -1){
        system='OPiOS';
    }
    return system+'|'+broName;
}
//字母数字随机码
function RandomCode(num){
    var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var nums="";
    for(var i=0;i<num;i++){
        var id = parseInt(Math.random()*61);
        nums+=chars[id];
    }
    return nums;
}
//返回上一页
function back() {
    window.history.back(-1);
}
//类jquery选择器封装。
function $_(dom) {
    switch (dom){
        case dom.indexOf('#')>-1:
            return document.querySelector(dom);
            break;
        default:
            return document.querySelectorAll(dom);
    }
}
//常见的服务器错误返回(JQ ajax)
// contentType:"application/x-www-form-urlencoded;charset=utf-8",
//     complete:function(XMLHttpRequest,textStatus){
//     if(textStatus=='timeout'){
//         ajaxTimeoutTest.abort();
//         alert("超时");
//     }
// },
function serverErr() {
    return {
        301:function () {
            alert('(code:301)永久重定向。');
        },
        302:function () {
            alert('(code:302)临时重定向。');
        },
        303:function () {
            alert('(code:303)请求资源存在另一个URI。');
        },
        304:function () {
            alert('(code:304)不包含任何响应主体。');
        },
        307:function () {
            alert('(code:307)临时重定向。');
        },
        400:function () {
            alert('(code:400)报文存在语法错误或参数错误。');
        },
        401:function () {
            alert('(code:401)发送的请求需要有HTTP认证信息或者是认证失败。');
        },
        403:function () {
            alert('(code:403)禁止访问。');
        },
        404: function() {
            alert('(code:404)数据获取/输入失败，没有此服务。');
        },
        500: function() {
            alert('(code:500)服务器故障或Web应用故障。');
        },
        503:function () {
            alert('(code:503)服务器超负载或停机维护。');
        },
        504: function() {
            alert('(code:504)数据获取/输入失败，服务器没有响应。');
        },
    }
}

function urlencode(str){
    var res = encodeURIComponent(str);

    //0~9 a~z A~Z -_.
    res = res.replace(/[^0-9a-zA-Z\-_\.%]/g, function ($0) {
        //不用考虑一位数了
        return '%' + $0.charCodeAt(0).toString(16).toUpperCase();
    });
    return res;
}

function ready(fn) {
    if(document.addEventListener) {
        document.addEventListener('DOMContentLoaded', function() {
            //注销事件, 避免反复触发
            document.removeEventListener('DOMContentLoaded',arguments.callee, false);
            fn();            //执行函数
        }, false);
    }else if(document.attachEvent) {        //IE
        document.attachEvent('onreadystatechange', function() {
            if(document.readyState == 'complete') {
                document.detachEvent('onreadystatechange', arguments.callee);
                fn();        //函数执行
            }
        });
    }
}
//alert无 url 地址；
function nourl() {
    var wAlert = window.alert;
    window.alert = function (message) {
        try {
            var iframe = document.createElement("IFRAME");
            iframe.style.display = "none";
            iframe.setAttribute("src", 'data:text/plain,');
            document.documentElement.appendChild(iframe);
            var alertFrame = window.frames[0];
            var iwindow = alertFrame.window;
            if (iwindow == undefined) {
                iwindow = alertFrame.contentWindow;
            }
            iwindow.alert(message);
            iframe.parentNode.removeChild(iframe);
        }
        catch (exc) {
            return wAlert(message);
        }
    }

    var wConfirm = window.confirm;
    window.confirm = function (message) {
        try {
            var iframe = document.createElement("IFRAME");
            iframe.style.display = "none";
            iframe.setAttribute("src", 'data:text/plain,');
            document.documentElement.appendChild(iframe);
            var alertFrame = window.frames[0];
            var iwindow = alertFrame.window;
            if (iwindow == undefined) {
                iwindow = alertFrame.contentWindow;
            }
            var result=iwindow.confirm(message);
            iframe.parentNode.removeChild(iframe);
            return result;
        }
        catch (exc) {
            return wConfirm(message);
        }
    }
}



//先根据rank排序，再根据age排序，最后根据name排序
// data.sort(compare('rank', compare('age', compare('name'))));
function compare(name, minor) {
    return function (o, p) {
        var a, b;
        if (o && p && typeof o === 'object' && typeof p === 'object') {
            a = o[name];
            b = p[name];
            if (a === b) {
                return typeof minor === 'function' ? minor(o, p) : 0;
            }
            if (typeof a === typeof b) {
                return a < b ? -1 : 1;
            }
            return typeof a < typeof b ? -1 : 1;
        } else {
            thro("error");
        }
    }
}


//截图*****

//绘制显示图片
function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png"); //生成图片地址
    return image;
}
//生成canvas元素
function convertImageToCanvas(image, startX, startY, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width =  width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(image, startX, startY, width, height, 0, 0, width, height);//在这调整图片中内容的显示（大小,放大缩小,位置等）
    return canvas;
}

// 另存为图片
function download(src,file_name) {
    var random = RandomNum(1000000,9999999);
    random = 'a' +random;
    var href = $("<a id='"+random+"' target='_blank'></a>").attr("href", src).attr("download", file_name+".jpg");
    href.appendTo($("body"));
    href[0].click();

}


function DownLoadReportIMG(fileName,imgPathURL) {
    var blob = base64Img2Blob(imgPathURL);
    //ie10及以上
    console.log(blob);
    window.navigator.msSaveBlob(blob, fileName);
}

function base64Img2Blob(code){
    var parts = code.split(';base64,');
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;
    var uInt8Array = new Uint8Array(rawLength);
    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {type: contentType});
}

//截图*****



// (isiOS==true) ? window.webkit.messageHandlers.paymentResult.postMessage(data.err_code) : androidJS.paymentResult(data.err_code);

//可用的上传文件检测。
// $("#upinput").change(function () {
//     var obj=$("#upinput")[0].files[0];
//     var type=self.files[0].type
//       type=type.split('/')
//     var size=Math.round($("#upinput")[0].files[0].size/1024*100)/100
//     var fr=new FileReader();
//     fr.onload=function (data) {
//         $("#upk img").remove();
//         $("#upk span").remove();
//         $("#upload span").html('更改图片');
//         var img=$('<img src="'+this.result+'"/>');
//         $("input[name='imgurl']").val(this.result);
//         img.appendTo($("#upk"));
//     };
//     fr.readAsDataURL(obj);
// })



//function upload(filesize,self){
//    var type=self.files[0].type
//    type=type.split('/')
//
//    if(type[0]!='image'){
//        return '请上传图片文件！'
//    }
//    else  if(size>filesize){
//        return '请上传小于600kb的图片！'
//    }
//    else {
//        var oFReader = new FileReader();
//        oFReader.readAsDataURL(self.files[0]);
//        oFReader.onload = function (oFREvent) {
//            return oFREvent
//            //.target.result
//        };
//    }
//}

//base64位 本地预览图片
// $("#upinput").change(function () {
//     var obj=$("#upinput")[0].files[0];
//     var type=obj.type;
//     type=type.split('/');
//     var size=Math.round(obj.size/1024*100)/100
//     $("#upload").hide();
//     $("#upthen").show();
//     if(type[0]!='image'){
//         return '请上传图片文件'
//     }
//     else if(size>5120){
//         return '请上传小于5M的图片！'
//     }
//     else{
//         var fr=new FileReader();
//         fr.onload=function (data) {
//             $("#upk img").remove();
//             $("#upk span").remove();
//             var img=$('<img src="'+this.result+'"/>');
//             img.appendTo($("#upk"));
//         };
//         fr.readAsDataURL(obj);
//     }
// });



/**
 *
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　 ┣┓
 * 　　　　┃　　　　 ┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 *
 */